package com.lsh.service.impl;

import com.lsh.common.HealthException;
import com.lsh.dao.OrderSettingDao;
import com.lsh.pojo.OrderSetting;
import com.lsh.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Override
    @Transactional
    public void add(List<OrderSetting> orderSettingList) {
        //先遍历
        for (OrderSetting orderSetting : orderSettingList) {
            //先查看日期在数据库中是否存在
            OrderSetting orderSettingDB = orderSettingDao.findByOrderDate(orderSetting.getOrderDate());
            if(orderSettingDB != null){
                //说明数据库中有次日期   已预约数量不能大于可预约数量
                if (orderSettingDB.getReservations() > orderSetting.getNumber()){
                    //已预约数量大于可预约数量
                    throw new HealthException(orderSetting.getOrderDate()+"此日期已经预约的人数超过要设置的预约数");
                }else {
                    orderSettingDao.updateNumber(orderSetting);
                }
            }else {
                orderSettingDao.add(orderSetting);
            }
        }
    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {
        String dateBegin = date+"-0";
        String dateEnd = date+"-35";
        List<Map> mapList = orderSettingDao.getOrderSettingByMonth(dateBegin,dateEnd);
        Calendar instance = Calendar.getInstance();
        for (Map map : mapList) {
            Date date1 = new Date();
            instance.setTime((Date)(map.get("orderDate")));
            map.put("date",String.valueOf(instance.get(Calendar.DATE)));
        }
        return mapList;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //先查看日期在数据库中是否存在
        OrderSetting orderSettingDB = orderSettingDao.findByOrderDate(orderSetting.getOrderDate());
        if(orderSettingDB != null){
            //说明数据库中有次日期   已预约数量不能大于可预约数量
            if (orderSettingDB.getReservations() > orderSetting.getNumber()){
                //已预约数量大于可预约数量
                throw new HealthException(orderSetting.getOrderDate()+"此日期已经预约的人数超过要设置的预约数");
            }else {
                orderSettingDao.updateNumber(orderSetting);
            }
        }else {
            orderSettingDao.add(orderSetting);
        }
    }
}
